//$URL: http://dasding.googlecode.com/svn/trunk/api/src/main/java/de/piratech/dasding/api/rest/ActionIdResource.java $
//$Id: ActionIdResource.java 128 2013-04-07 22:17:09Z krieg.maria@gmail.com $
/*
 * Copyright 2012 Piratech.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.piratech.dasding.api.rest;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import de.piratech.dasding.data.Action;
import de.piratech.dasding.data.User;
import de.piratech.dasding.data.database.DatabaseException;
import de.piratech.dasding.security.annotations.RequireUserRole;

/**
 * Resource for all calls for an specific action
 * 
 * @author deveth0
 */
@Path("/actions/id/{id}")
@Component
public class ActionIdResource extends AbstractResource {

  private static final Logger LOG = LoggerFactory
      .getLogger(ActionIdResource.class);

  /**
   * Returns a single action by id
   * 
   * http://localhost:8080/dasding.api/api/actions/id/1
   * 
   * GET
   * 
   * @param id
   * @return
   */
  @GET
  @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  public Action getAction(@PathParam("id") String id) {
    LOG.debug("getAction({})", id);
    try {
      return getActionData().getAction(id);
    } catch (DatabaseException dbe) {
      throw getBadRequestException(dbe);
    }
  }

  /**
   * Returns a single action by id
   * 
   * http://localhost:8080/dasding.api/api/actions/id/1
   * 
   * GET
   * 
   * @param id
   * @return
   * @throws DatabaseException
   */
  @PUT
  @Path("/participate")
  @RequireUserRole(roles = User.USER_ROLE.USER)
  @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  public Action participate(@PathParam("id") String id,
      @Context SecurityContext pSecurityContext) throws DatabaseException {
    LOG.debug("participate {}", id);
    Action action = getAction(id);
    User user = getUserFromSecurityContext(pSecurityContext);
    action.addParticipant(user);
    getActionData().updateAction(action);
    return getAction(id);
  }

  /**
   * Updates the Action with the given id
   * 
   * http://localhost:8080/dasding.api/api/actions/id/1
   * 
   * PUT
   * 
   * @param pId
   * @param pName
   * @param pDescription
   * @param pTime
   * 
   * @return
   */
  @PUT
  public Response updateAction(@PathParam("id") String pId,
      @QueryParam("name") String pName,
      @QueryParam("description") String pDescription,
      @QueryParam("time") String pTime,
      @Context SecurityContext pSecurityContext) {
    LOG.debug("updateAction(id={}, name={}, description={}, time={})", pId,
        pName, pDescription, pTime);
    try {
      Action action = getActionData().getAction(pId);
      if (action == null) {
        return getBadRequestResponse("action does not exist");
      }
      if (StringUtils.isNotBlank(pName)) {
        action.setName(pName);
      }
      if (StringUtils.isNotBlank(pDescription)) {
        action.setDescription(pDescription);
      }
      if (pTime != null) {
        // TODO: string in date umwandeln oder date als long
        // anstatt date.tostring senden
        // action.setTime(new Date(pTime));
      }
      if (!action.isValid()) {
        throw new IllegalArgumentException("action not valid");
      }
      getActionData().updateAction(action);
      return getNoContentResponse();
    } catch (DatabaseException dbe) {
      return getBadRequestResponse(dbe);
    }
  }

  /**
   * Sets the given action to status "Canceled"
   * 
   * http://localhost:8080/dasding.api/api/action/id/1
   * 
   * DELETE
   * 
   * @param id
   */
  @DELETE
  @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  @RequireUserRole(roles = User.USER_ROLE.USER)
  public Response deleteAction(@PathParam("id") String id,
      @Context SecurityContext pSecurityContext) {
    LOG.debug("deleteAction({})", id);
    try {
      Action action = getActionData().getAction(id);
      User user = action.getResponsible();
      if (!user.getId().equals(
          ((User) pSecurityContext.getUserPrincipal()).getId())) {
        return getBadRequestResponse("user is not responsible");
      }
      action.setStatus(Action.ACTIONSTATUS.CANCELED);
      getActionData().updateAction(action);
      return getNoContentResponse();
    } catch (DatabaseException e) {
      return getBadRequestResponse(e);
    }
  }

  @Override
  protected Logger getLogger() {
    return LOG;
  }
}
